<template>
    <div class="page">
        <el-row style="padding-bottom: 10px;">
            <el-col :span="6">
                <el-input placeholder="关键字搜索" v-model="searchParams.keyWord">
                    <el-button slot="append" icon="el-icon-search" @click="searchBtn"></el-button>
                </el-input>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24" style="padding: 10px 0px 10px 0px;text-align: right;border-top: 1px solid #e4e7ed;">
                <el-button size="small" type="primary" icon="el-icon-edit-outline" @click="openAddDrawer">添加</el-button>
                <el-button size="small" type="primary" icon="el-icon-edit" @click="openUpdateDrawer"
                           :disabled="selectRows.length!==1">编辑
                </el-button>
                <el-button size="small" type="primary" icon="el-icon-info" @click="openUpdateDrawer"
                           :disabled="selectRows.length!==1">详情
                </el-button>
                <el-button size="small" type="primary" icon="el-icon-delete" @click="removeBtn"
                           :disabled="selectRows.length===0">删除
                </el-button>
            </el-col>
            <el-col :span="24" style="padding-bottom: 10px;">
                <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"/>
                    <el-table-column fixed prop="imgUrl" label="课程封面" width="200">
                        <template slot-scope="scope">
                            <span v-if="scope.row.imageUrl">
                                <el-image
                                    fit="fill"
                                    style="width: 50px; height: 50px"
                                    :src="baseUrl+scope.row.imageUrl"
                                    :preview-src-list="[baseUrl+scope.row.imageUrl]">
                                </el-image>
                            </span>
                            <span v-else @click="selectRows=[];selectRows[0]=scope.row">
                                封面未上传
                                <el-upload
                                    class="upload-demo"
                                    :action="uploadUrl"
                                    :show-file-list="false"
                                    :on-preview="handlePreview"
                                    :on-remove="handleRemove"
                                    :before-remove="beforeRemove"
                                    :on-exceed="handleExceed"
                                    :on-success="onSuccess">
                                        <el-link type="primary" href="javascript:void(0)">
                                        (<i class="el-icon-upload"/>点击上传)
                                        </el-link>
                                    </el-upload>
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="课程名称" width="200"></el-table-column>
                    <el-table-column prop="courseTypeId" label="课程类型" width="200">
                        <template slot-scope="scope">
                            {{ CollectionLabel('COURSETYPE', scope.row.courseTypeId) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="课程简介"></el-table-column>
                </el-table>
            </el-col>
            <el-col :span="24" style="text-align: center;">
                <el-pagination background layout="prev, pager, next" :total="paginationCofig.total"
                               @size-change="sizeChange" :pageSize="paginationCofig.pageSize"
                               :currentPage.sync="paginationCofig.currentPage" @current-change="currentChange"
                               @prev-click="prevClick" @next-click="nextClick"></el-pagination>
            </el-col>
        </el-row>


        <!-- 新增 -->
        <el-drawer title="新增" :visible.sync="isAddDrawer" direction="rtl" :wrapperClosable="false"
                   :close-on-press-escape="false" :show-close="false">
            <el-row style="height: calc(100% - 42px);">
                <el-form :model="addForm" :rules="rules" ref="addForm" label-width="100px">
                    <el-form-item label="课程名称" prop="name">
                        <el-input v-model="addForm.name" placeholder="课程名称" style="width: 80%;"></el-input>
                    </el-form-item>
                    <el-form-item label="课程类型" prop="courseTypeId">
                        <el-select v-model="addForm.courseTypeId" placeholder="课程类型" style="width: 80%;">
                            <el-option v-for="item in CollectionData('COURSETYPE')" :value="item.value"
                                       :label="item.label" :key="item.value"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="备注信息" prop="remark">
                        <el-input
                            v-model="addForm.remark"
                            type="textarea"
                            :autosize="{ minRows: 4, maxRows: 8}"
                            placeholder="备注信息"
                            style="width: 80%;">
                        </el-input>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row style="height: 42px;text-align: right;border-top: 1px solid #e4e7ed;padding-top: 10px;">
                <el-button size="small" type="primary" icon="el-icon-check" @click="addSave">保存</el-button>
                <el-button size="small" icon="el-icon-refresh-right" @click="resetForm('addForm')">重置</el-button>
                <el-button size="small" type="danger" icon="el-icon-close" @click="isAddDrawer=false">关闭</el-button>
            </el-row>
        </el-drawer>
        <!-- 编辑 -->
        <el-drawer title="编辑" :visible.sync="isUpdateDrawer" direction="rtl" :wrapperClosable="false"
                   :close-on-press-escape="false" :show-close="false">
            <el-row style="height: calc(100% - 42px);">
                <el-form :model="updateForm" :rules="rules" ref="updateForm" label-width="100px">
                    <el-form-item label="课程名称" prop="name">
                        <el-input v-model="updateForm.name" placeholder="课程名称" style="width: 80%;"></el-input>
                    </el-form-item>
                    <el-form-item label="课程类型" prop="courseTypeId">
                        <el-select v-model="updateForm.courseTypeId" placeholder="课程类型" style="width: 80%;">
                            <el-option v-for="item in CollectionData('COURSETYPE')" :value="item.value"
                                       :label="item.label" :key="item.value"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="备注信息" prop="remark">
                        <el-input
                            v-model="updateForm.remark"
                            type="textarea"
                            :autosize="{ minRows: 4, maxRows: 8}"
                            placeholder="备注信息"
                            style="width: 80%;">
                        </el-input>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row style="height: 42px;text-align: right;border-top: 1px solid #e4e7ed;padding-top: 10px;">
                <el-button size="small" type="primary" icon="el-icon-check" @click="updateSave">保存</el-button>
                <el-button size="small" icon="el-icon-refresh-right" @click="resetForm('updateForm')">重置</el-button>
                <el-button size="small" type="danger" icon="el-icon-close" @click="isUpdateDrawer=false">关闭</el-button>
            </el-row>
        </el-drawer>
        <!-- 详情 -->
        <el-drawer title="详情" :visible.sync="isDetailDrawer" direction="rtl">
            <span>我来啦!</span>
        </el-drawer>

    </div>
</template>

<script>
const qs = require("qs")
import $api from '@/api/course'
import _ from 'lodash'

const formObj = {
    name: '',
    courseTypeId: '',
    remark: '',
}
export default {
    data() {
        return {
            uploadUrl: $api.uploadUrl,
            /*搜索框*/
            searchParams: {
                keyWord: '',
            },
            /* 分页tiao */
            paginationCofig: {
                pageSize: 10,
                currentPage: 1,
                total: 0,
            },
            /* 表格data */
            tableData: [],
            selectRows: [],
            /* 抽屉 */
            isAddDrawer: false,
            isUpdateDrawer: false,
            isDetailDrawer: false,
            /* 表单 */
            addForm: null,
            updateForm: null,
            rules: {
                name: [
                    {type: 'string', required: true, message: '请输入课程名称', trigger: 'blur'},
                    {min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur'}
                ],
                courseTypeId: [
                    {type: 'string', required: true, message: '请选择课程类型', trigger: 'blur',},
                ],
                remark: [
                    {type: 'string', required: true, message: '请填写课程简介', trigger: 'blur'},
                ],

            }
        };
    },
    methods: {
        searchBtn() {
            this.pageList(qs.stringify(this.searchParams))
        },
        handleSelectionChange(val) {
            this.selectRows = val
        },
        /* 新增抽屉 */
        openAddDrawer() {
            this.isAddDrawer = true
        },
        /* 修改抽屉 */
        openUpdateDrawer() {
            this.isUpdateDrawer = true
        },
        updateSave() {
            this.validateForm("updateForm", (success, errorObj) => {
                if (success) {
                    const id = this.selectRows[0].id
                    const formData = this.updateForm
                    $api.update({id, ...formData}).then(data => {
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        });
                        this.isUpdateDrawer = false
                        this.pageList()
                    })
                }
            })
        },
        /* 详情抽屉 */
        openDetailDrawer() {
            this.isDetailDrawer = true
        },
        /*删除按钮*/
        removeBtn() {
            // console.log(this.selectRows)
            this.$confirm('你正在删除当前选中的课程, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const ids = this.selectRows.map(item => item.id).join(",")
                $api.deleteByIds(ids).then(data => {
                    this.$message.success("删除成功")
                    this.pageList()
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });

        },
        /* 分页条-start */
        sizeChange(pageSize) {
            this.pageList()
        },
        currentChange(currentPage) {
            this.pageList()
        },
        prevClick(pageSize) {
            this.pageList()
        },
        nextClick(currentPage) {
            this.pageList()
        },
        /*文件上传*/
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        onSuccess(response, file, fileList) {
            if (response && response.code == 200) {
                const url = response.data.url
                let course = this.selectRows[0]
                $api.updateImgUrl({id: course.id, imageUrl: url}).then(data => {
                    this.$message({
                        message: '上传图片成功',
                        type: 'success'
                    });
                    this.pageList()
                })
            }

        },
        /* api */

        pageList(query) {
            const currentPage = this.paginationCofig.currentPage
            const pageSize = this.paginationCofig.pageSize
            $api.listPage(currentPage, pageSize, query).then(data => {
                // console.log(data.data);
                this.paginationCofig.total = data.data.total

                this.tableData = data.data.records
            })

        },
        addSave() {
            this.validateForm("addForm", (success, errorObj) => {
                if (success) {
                    const formData = this.addForm
                    // console.log(formData)
                    $api.add(formData).then(data => {
                        this.$message({
                            message: '新增成功',
                            type: 'success'
                        });
                        this.isAddDrawer = false
                        this.pageList()
                    })
                }
            })
        },

        /* common methods */
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        validateForm(formName, callback) {
            this.$refs[formName].validate(callback);
        },
    },
    watch: {
        isUpdateDrawer(val) {
            if (val) {
                const id = this.selectRows[0].id
                $api.queryOne(id).then(data => {
                    const resData = data.data
                    Object.keys(this.updateForm).forEach(key => {
                        if (resData[key]) {
                            this.updateForm[key] = resData[key]
                        }
                    })
                    // console.log(this.updateForm)
                })
            }
        }
    },
    mounted() {
        this.pageList()
    },
    created() {
        this.addForm = {}
        this.updateForm = {}
        this.addForm = _.cloneDeep(formObj)
        this.updateForm = _.cloneDeep(formObj)
    }
};
</script>

<style scoped="scoped">
.upload-demo {
    display: inline-block;
}
</style>